// 代码块 importM
import 'dart:async';

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false, // 去掉debugger图标
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const HomePage(),
    );
  }
}

// 父widget
class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  final _globalKey = GlobalKey<AnimatedListState>();
  bool flag = true;
  List<String> list = ["第一条", "第二条"];

  Widget _buildItem(index) {
    return ListTile(
      title: Text(list[index]),
      trailing: IconButton(
          onPressed: () {
            // 执行删除
            _deleteItem(index);
          },
          icon: const Icon(Icons.delete)),
    );
  }

  void _deleteItem(index) {
    if (flag == true) {
      flag = false;
      _globalKey.currentState!.removeItem(index, (context, animation) {
        list.removeAt(index); // 数组删除数据
        var removeItem = _buildItem(index);
        return FadeTransition(
          opacity: animation,
          child: removeItem,
        ); // 执行动画的元素
      });

      // 解决快速删除的bug
      Timer.periodic(Duration(milliseconds: 500), (timer) {
        flag = true;
        timer.cancel();
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text("Title"),
        ),
        floatingActionButton: FloatingActionButton(
            child: const Icon(Icons.add),
            onPressed: () {
              setState(() {
                list.add("我是新增的数据");
                _globalKey.currentState!.insertItem(list.length - 1);
              });
            }),
        body: AnimatedList(
            key: _globalKey,
            initialItemCount: list.length,
            itemBuilder: ((context, index, animation) {
              return FadeTransition(
                opacity: animation,
                child: _buildItem(index),
              );
            })));
  }
}
